/******************************************************************************
 * Copyright (C) 2017 Chengdu Dlhd information industry co. LTD.
 * All Rights Reserved.
 * 本软件为成都顶联互动信息产业有限公司开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、复制、修改或发布本软件.
 *****************************************************************************/
package net.dgg.dggcloud.service.jrcrm.service.business;

import com.alibaba.fastjson.JSONObject;
import net.dgg.dggcloud.core.cache.CacheManager;
import net.dgg.dggcloud.core.constants.Constants;
import net.dgg.dggcloud.core.json.JsonUtil;
import net.dgg.dggcloud.core.util.ConfigLoader;
import net.dgg.dggcloud.core.util.DateUtil;
import net.dgg.dggcloud.core.util.StringUtils;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.common.exception.BizException;
import net.dgg.dggcloud.service.common.pagination.PageData;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.jrcrm.constant.*;
import net.dgg.dggcloud.service.jrcrm.dao.business.BusinessDao;
import net.dgg.dggcloud.service.jrcrm.dao.business.ReferralRecordDao;
import net.dgg.dggcloud.service.jrcrm.dao.cms.WorkDayDao;
import net.dgg.dggcloud.service.jrcrm.dao.customer.ContactDao;
import net.dgg.dggcloud.service.jrcrm.entity.business.*;
import net.dgg.dggcloud.service.jrcrm.entity.cms.ChannelCost;
import net.dgg.dggcloud.service.jrcrm.entity.cms.TreeBook;
import net.dgg.dggcloud.service.jrcrm.entity.cms.UserSetting;
import net.dgg.dggcloud.service.jrcrm.entity.customer.*;
import net.dgg.dggcloud.service.jrcrm.service.cms.*;
import net.dgg.dggcloud.service.jrcrm.service.customer.DepartmentCustomerService;
import net.dgg.dggcloud.service.jrcrm.service.customer.WhiteListService;
import net.dgg.dggcloud.service.jrcrm.service.customer.WidelyResourceService;
import net.dgg.dggcloud.service.jrcrm.service.customer.api.ContactApiService;
import net.dgg.dggcloud.service.jrcrm.service.customer.api.CustomerApiService;
import net.dgg.dggcloud.service.jrcrm.utils.BizExceptionUtil;
import net.dgg.dggcloud.service.jrcrm.utils.HttpRequest;
import net.dgg.dggcloud.service.jrcrm.utils.TranslateMapUtil;
import net.dgg.dggcloud.service.jrcrm.vo.BusinessAddVo;
import net.dgg.dggcloud.service.service.RoleService;
import net.dgg.dggcloud.service.service.organization.OrganizationService;
import net.dgg.dggcloud.service.service.user.UserService;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.hibernate.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @ClassName 〈BusinessReferralService>
 * @Description
 * @Author 罗金
 * @Date 2018/1/11 11:42
 */
@Service
public class BusinessReferralService extends BaseService {
    @Resource
    private CustomerApiService customerApiService;
    @Resource
    private RuleConfigService ruleConfigService;
    @Resource
    private ContactApiService contactApiService;
    @Resource
    private BillNumberRuleService billNumberService;
    @Resource
    private UserService userService;
    @Resource
    private OrganizationService organizationService;
    @Resource
    private BusinessDao businessDao;
    @Resource
    private CustomerRecordService customerRecordService;
    @Resource
    private ContactDao contactDao;

    @Resource
    private BusinessService businessService;
    @Resource
    private BusinessReferralService businessReferralService;
    @Resource
    protected MessageService messageService;
    @Resource
    private RoleService roleService;
    @Resource
    private DepartmentCustomerService departmentCustomerService;
    @Resource
    private TreeBookService treeBookService;
    @Resource
    private WidelyResourceService widelyResourceService;
    @Resource
    private WhiteListService whiteListService;
    @Resource
    private ReferralRecordDao referralRecordDao;
    @Resource
    private WorkDayDao workDayDao;

    /**
     * 转介绍商机核款记录统计
     */
    Integer countReferralRecordByMap(Map map){
        return referralRecordDao.countReferralRecordByMap(map);
    };
    /**
     * 转介绍商机核款list
     */
    public List<Map> listReferralRecordByMap(Map map){
        return referralRecordDao.listReferralRecordByMap(map);
    };

    /**
     * 转介绍记录条数</br>
     *
     * @param map </br>
     * @return 记录 </br>
     */
    public Integer countReferralBusinessByMap(Map map) {
        return businessDao.countReferralBusinessByMap(map);
    }

    /**
     * 转介绍List<Map></br>
     *
     * @param map</br>
     * @return 集合</br>
     */
    public List<Map> listReferralBusinessByMap(Map map) {
        return businessDao.listReferralBusinessByMap(map);
    }


    /**
     * 转介绍提成记录条数</br>
     *
     * @param map </br>
     * @return 记录 </br>
     */
    public Integer countReferralOrderBusinessByMap(Map map) {
        return businessDao.countReferralOrderBusinessByMap(map);
    }

    /**
     * 转介绍提成List<Map></br>
     *
     * @param map</br>
     * @return 集合</br>
     */
    public List<Map> listReferralOrderBusinessByMap(Map map) {
        return businessDao.listReferralOrderBusinessByMap(map);
    }

    /**
     * 已签单记录条数</br>
     *
     * @param map </br>
     * @return 记录 </br>
     */
    public Integer countOrderBusinessByMap(Map map) {
        return businessDao.countOrderBusinessByMap(map);
    }

    /**
     * 已签单List<Map></br>
     *
     * @param map</br>
     * @return 集合</br>
     */
    public List<Map> listOrderBusinessByMap(Map map) {
        return businessDao.listOrderBusinessByMap(map);
    }

    /**
     * 根据条件统计商机数量
     *
     * @param map
     * @return
     */
    public Integer countBusinessByMap(Map map) {
        return businessDao.countBusinessByMap(map);
    }


    /**
     * 跟进中的商机列表，因为查询sql的原因，单独对这个列表写了一个sql
     *
     * @param map
     * @return
     */
    public List<Map> listFollowingBusiness(Map map) {
        return businessDao.listFollowingBusiness(map);
    }

    /**
     * 根据条件查询商机列表
     *
     * @param map
     * @return
     */
    public List<Map> listBusinessByMap(Map map) {
        return businessDao.listBusinessByMap(map);
    }


    /**
     * 根据id获取商机
     *
     * @param busId
     * @return
     */
    public Boolean addReferralRecord(Long busId,ReferralRecord referralRecord ) {
        BusinessReferral businessReferral = repository.get(BusinessReferral.class,busId);
        if (null == businessReferral) {
            throw new BizException("商机为空，无法操作", 10001);
        }
        try {
        Long id = keyWorker.nextId();
        referralRecord.setId(id);
        referralRecord.setPerformanceProportion(businessReferral.getPerformanceProportion());
        referralRecord.setTcProportion(businessReferral.getTcProportion());
        referralRecord.setStatus(0);
        referralRecord.setCreateTime(new Date());
        referralRecord.setTcRedMoney((referralRecord.getPerformanceProportionMoney()*businessReferral.getTcProportion())/100);
        referralRecord.setTcProportionMoney((referralRecord.getPerformanceProportionMoney()*businessReferral.getTcProportion())/100);
        repository.save(referralRecord);
        } catch (BizException e) {
            throw new BizException("保存核款失败", 10001);
        }
        return true;
    }


      /**
     * 根据id获取商机
     *
     * @param busId
     * @return
     */
    public BusinessReferral getBusinessReferralById(Long busId) {
        return repository.get(BusinessReferral.class, busId);
    }

    /**
     * 根据id获取发放记录
     *
     * @param busId
     * @return
     */
    public ReferralRecord getReferralRecordById(Long busId) {
        return repository.get(ReferralRecord.class, busId);
    }

    /**
     * 根据id获取商机
     *
     * @param busId
     * @return
     */
    public Business getBusinessById(Long busId) {
        return repository.get(Business.class, busId);
    }

    /**
     * 新增商机。资源端、商务个人、广泛资源转化、白名单、新媒体接口都使用该方法新增商机
     *
     * @param reqParam 页面参数
     * @param business 页面传入的商机信息
     * @param user     当前操作用户
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Long saveAddNewBusiness(Map reqParam, Business business, BusinessReferral businessReferral, User user) {
        if (null == business) {
            throw new BizException("商机为空，无法操作", 10001);
        }
        if (null == business.getTypeCode()) {
            throw new BizException("商机业态为空，无法操作", 10001);
        }
        if (null == user) {
            throw new BizException("新增人为空，无法操作", 10001);
        }
        String areaName = reqParam.get("areaName") == null ? "" : reqParam.get("areaName").toString();
        if (StringUtils.isBlank(areaName)) {
            throw new BizException("业务区域为空，无法操作", 10001);
        }
        String contactWay = reqParam.get("contactWay") == null ? "" : reqParam.get("contactWay").toString();
        String no = billNumberService.updateBillNumberByCode("SJ");//商机单据号
        Long customerId = business.getCustomerId();
        Long businessId =  keyWorker.nextId();

        business.setId(businessId);
        business.setAddTypeCode( BusinessConstant.BUS_ADD_TYPE_CODE_7);
        businessReferral.setId(businessId);
        businessReferral.setIsReceive(1);
        String customerPhone = business.getCustomerPhone();
        User referralUser  = userService.getUserById(businessReferral.getReferralUserId());//转介绍人
        User receiveUser  = userService.getUserById(businessReferral.getReceiveUserId());//接收人
        businessReferral.setReceiveUserName(receiveUser.getName()+receiveUser.getLoginName());
        businessReferral.setReceiveOrgId(receiveUser.getOrgId());
        businessReferral.setReferralUserName(referralUser.getName()+referralUser.getLoginName());
        businessReferral.setReferralOrgId(referralUser.getOrgId());
        businessReferral.setCreateUser(user);
        businessReferral.setCreateType(1);

        if(null != reqParam.get("referralStartTime") && StringUtils.isNotBlank(reqParam.get("referralStartTime").toString())) {
           //businessReferral.setCreateTime(DateUtil.stringDateToDate(reqParam.get("referralStartTime") + "", "yyyy-MM-dd HH:mm:ss"));
            businessReferral.setReferralTime(DateUtil.stringDateToDate(reqParam.get("referralStartTime") + "", "yyyy-MM-dd HH:mm:ss"));
        }
        businessReferral.setReturnNum(0);
        Long orgId = organizationService.getOrganizationDepartmentId(referralUser.getOrgId());
        businessReferral.setReferralOrganizationId(orgId);
        if(!TranslateMapUtil.translateOrgName(orgId).equals("null")&&TranslateMapUtil.translateOrgName(orgId).length()>0) {
            businessReferral.setReferralOrganizationName(TranslateMapUtil.translateOrgName(orgId));
        }
        Customer customer = null;
        //判断是否传入客户的id，如果有，则从数据库中找,没有再根据电话号码和类型查找
        if (null != customerId) {
            customer = customerApiService.getCustomerById(customerId);
        }
        if (null == customer) {//根据id没有查到客户，再根据号码去查
            if (StringUtils.isBlank(contactWay)) {
                throw new BizException("客户联系号码类型不能为空", 10001);
            }
            if (StringUtils.isBlank(customerPhone)) {
                throw new BizException("客户号码不能为空", 10001);
            }

            Map param = new HashMap();
            param.put("contactWay", contactWay);
            param.put("customerNumber", customerPhone);
            List<Map> cusList = customerApiService.queryCustomerListByParams(param);
            if (null != cusList && !cusList.isEmpty()) {
                customer = customerApiService.getCustomerById(Long.valueOf(cusList.get(0).get("id").toString()));
            }
        }

        Map cus = new HashMap();
        cus.put("name", business.getCustomerName());
        cus.put("customerNumber", business.getCustomerPhone());
        cus.put("contactWay", contactWay);
        cus.put("customerType", 1);

        businessReferral.setRewardWay(reqParam.get("rewardWay").toString());
        if(StringUtils.isNotBlank(reqParam.get("referralRed")+"")){
            businessReferral.setReferralRed(Long.parseLong((reqParam.get("referralRed")+"")));
        }

        businessReferral.setPerformanceProportion(Long.parseLong(reqParam.get("performanceProportion")+""));
        businessReferral.setTcProportion(Long.parseLong(reqParam.get("tcProportion")+""));
        cus.put("age", reqParam.get("age"));
        cus.put("address", reqParam.get("address"));
        cus.put("registeredResidence", reqParam.get("registeredResidence"));
        cus.put("email", reqParam.get("email"));
        cus.put("maritalStatus", reqParam.get("maritalStatus"));
        cus.put("birthday", reqParam.get("birthday"));
        cus.put("idCard", reqParam.get("idCard"));
        cus.put("sex", reqParam.get("sex"));
        cus.put("eduBackground", reqParam.get("eduBackground"));
        cus.put("origin", "BUS_LYQD_805");
        cus.put("originName", "转介绍");
        cus.put("User", user);
        cus.put("customerAttr", reqParam.get("customerAttr"));
        cus.put("contacts", reqParam.get("contacts"));
        cus.put("business", business);
        //没有则新增
        if (null == customer) {
//            Map  attrMap = new HashMap();
//            attrMap.put("customerPhone",cus.get("customerNumber"));
//            Query query = repository.getSession().createQuery("From CustomerForm where phone ='"+customerPhone+"'");
//            if(query.list().size()>0) {
//                CustomerForm cf = (CustomerForm) query.list().get(0);
//                business.setLoanAmount(cf.getMoney()*100);;
//            }
            // 客户新增
            Map cusMap = customerApiService.saveCustomer(cus);
            customer = (Customer) cusMap.get("data");
        } else {
            //客户存在则进行商机判重
            //统计商机状态不为退单且没有在事业部库、无效库都数量
            Map existed = new HashMap();
            existed.put("customerId", customer.getId()); //全部改为拾回
//            existed.put("notInBusinessLocation", String.valueOf(BusinessConstant.BUS_STORE_DEPARTMENT + "," + BusinessConstant.BUS_STORE_INVALID));
//            existed.put("notInBusinessStatus", "'" + BusinessConstant.BUS_STATUS_ORDER_BACK + "'");
            existed.put("notInBusinessLocation","6");
            TreeBook tb = treeBookService.queryTreeBookByCode(business.getTypeCode());
                //资源端新建
                if (tb.getExt5().equals(BusinessConstant.BUS_REPEAT_2)) { //事业部
                    existed.put("businessOrganizationId",business.getBusinessOrganizationId()+"");
                } else if (tb.getExt5().equals(BusinessConstant.BUS_REPEAT_1)) {//分公司
                 //   Long orgId = organizationService.getOrganizatioComploy(business.getBusinessOrganizationId());
                    existed.put("businessOrganizationId",business.getBusinessOrganizationId()+"");
                } else {//全集团

                }

            List<Map> list = businessDao.listBusinessByMap(existed);
            if (null != list && !list.isEmpty()) {
                // 客户商机跟进人为当前操作人，商机状态为已成单则可以新建商机，其他一律不能新建商机
//				for (Map map : list) {
//					boolean ex = !user.getId().toString().equals(String.valueOf(map.get("followerId")))
//							|| !BusinessConstant.BUS_STATUS_ORDER_SUCCESSED.equals(String.valueOf(map.get("businessStatus")));
//					 boolean ex =
//					 !BusinessConstant.BUS_STATUS_ORDER_SUCCESSED.equals(String.valueOf(map.get("businessStatus")));
//					BizExceptionUtil.isException(ex, "客户已有正在办理中的业务，不可以新建商机");
//				}
                existed.put("date", DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
               // String days = ruleConfigService.getRuleConfigByMap(1L, "GZ_BUS_SIGNED_ADD");
                if(NumberUtils.toInt(tb.getExt1())!=0)
                    existed.put("days",NumberUtils.toInt(tb.getExt1())+1);
                else
                    existed.put("days",NumberUtils.toInt(tb.getExt1()));
                String day = workDayDao.queryBeforeDate(existed);
                boolean ex = false;
                for (Map map : list) {
                    //在公共库不能新建商机
                    if(NumberUtils.toInt(map.get("businessLocation")+"")!=2&&NumberUtils.toInt(map.get("businessLocation")+"")!=5){
                        ex = true;
                        break;
                    }else {
                        //已签单多少天可以新建商机
                        boolean  businessStatus = BusinessConstant.BUS_STATUS_SIGNED.equals(String.valueOf(map.get("businessStatus")))||BusinessConstant.BUS_STATUS_ORDER_SUCCESSED.equals(String.valueOf(map.get("businessStatus")))||BusinessConstant.BUS_STATUS_ORDER_BACK.equals(String.valueOf(map.get("businessStatus")));
                        if (businessStatus) {
                            if (map.get("orderTime") != null) {
                                String orderTime = map.get("orderTime").toString();
                                int i = DateUtil.compare_date(day + " 00:00:00", orderTime);
                                if (i == 1) {
                                    ex = false;
                                } else {
                                    ex = true;
                                    break;
                                }
                            }

                        } else {
                            ex = true;
                        }
                    }
                }
                BizExceptionUtil.isException(ex, "客户已有正在办理中的业务，不可以新建商机");
            }


            cus.put("id", customer.getId());
            cus.put("contactWay", customer.getContactWay());
            customerApiService.updateCustomer(cus);
        }
        business.setIsReferral(1);
        businessReferral.setCustomerId(customer.getId());
        business.setOriginCode("BUS_LYQD_805");
        business.setDescription(HtmlUtils.htmlEscape(business.getDescription()));
        business.setCustomerAttr(customer.getCustomerAttrFlag());
        business.setCustomerId(customer.getId());
        business.setCustomerNo(customer.getNo());
        business.setCustomerWay(cus.get("contactWay").toString());
        business.setNo(no);
        business.setCreateUser(user);
        business.setOpportunitytypeCode(BusinessConstant.BUS_OPP_5);
        //默认为0的字段
        business.setIsImportant(1);
        business.setIsVip(0);
        business.setFollowTimes(0);
        business.setIsCost("CBJSFS_NO");//转介绍的不计算成本
        business.setCostPrice(0);
        business.setWayCode(BusinessConstant.BUS_WAY_CODE_4);//转介绍

        // 业务区域
        String[] area = areaName.split("/");
        if (area.length == 3) {
            business.setProvince(area[0].trim());
            business.setCity(area[1].trim());
            business.setArea(area[2].trim());
        } else if (area.length == 2) {
            business.setProvince(area[0].trim());
            business.setCity(area[1].trim());
        } else if (area.length == 1) {
            business.setProvince(area[0].trim());
        }

        //从事业部删除客户数据，更新白名单数据
        DepartmentCustomer dc = departmentCustomerService.getDepartmentCustomerByCustomerId(customer.getId());
        if (null != dc) {
            if (dc.getPushTime() != null) {
                Map whiteListMap = new HashMap();
                String pushMonth = DateUtil.dateToString(dc.getPushTime(), "yyyy-MM-dd");
                whiteListMap.put("month", pushMonth);
                whiteListMap.put("deptCusId", dc.getId());
                //查询所有白名单表
                List<WhiteList> wl = whiteListService.queryWhiteListByParam(whiteListMap);
                if (null != wl && wl.size() > 0) {
                    for (WhiteList whiteList : wl) {
                        whiteList.setUpdaterUser(user);
                        Integer status = whiteList.getPushUserId().longValue() == user.getId().longValue() ? 2 : 3;
                        whiteList.setStatus(status);
                        repository.saveOrUpdate(whiteList);
                    }
                }
            }
            repository.delete(dc);
        }
        //删除无效库中客户相关的数据
        Map imap = new HashMap();
        imap.put("customerId", customer.getId());
        businessDao.deleteInvalidCustomerByMap(imap);

        if (null != customer.getLastBusId()) {
            Business lastBusiness = repository.get(Business.class, customer.getId());
            if (null != lastBusiness && BusinessConstant.BUS_STATUS_ORDER_BACK.equals(lastBusiness.getBusinessStatus())) {
                //所在库为个人库，将强制掉库
                if (BusinessConstant.BUS_STORE_EMP.equals(lastBusiness.getBusinessLocation())) {
                    dropBusiness(lastBusiness, user, CustomerRecordConstant.BUS_OPERATE_BACKORDER_DROP);//强制掉库
                }
            }
            //客户的最后一条商机为成单商机，接收人默认为原商务
            if (null != lastBusiness && BusinessConstant.BUS_STATUS_ORDER_SUCCESSED.equals(lastBusiness.getBusinessStatus())) {
                //所在库为个人库，将强制掉库
                if (BusinessConstant.BUS_STORE_EMP.equals(lastBusiness.getBusinessLocation())) {
                    dropBusiness(lastBusiness, user, CustomerRecordConstant.BUS_OPERATE_ORDER_SUCCESS_DROP);//强制掉库
                }
            }
        }


        //如果是划分业绩，直接分给商务，如果是划分业绩及红包，进入质检待审核
        //分配转介绍商机
        if(StringUtils.isNotBlank(businessReferral.getRewardWay()) ) {
            if(businessReferral.getRewardWay().equals(BusinessConstant.REFERRAL_AWARD_WAY_HFYJ)){
                if(null != receiveUser.getDisableCutoffTime() && receiveUser.getDisableCutoffTime().getTime()>new Date().getTime()){
                    throw new BizException("商务在"+DateUtil.dateToString(receiveUser.getDisableCutoffTime(),"yyyy-MM-dd HH:mm:ss")+"之前处于被禁用状态，无法接收资源", 10001);
                }
                business.setIsReturn(CustomerRecordConstant.BUS_OPERATE_REFERRAL_RECEIVE);//接收
                allotReferralBusiness(business, receiveUser, user, referralUser,"1");
                //计算预计掉库时间
                businessService.setBusinessWillDropDate(business);
            }else if(businessReferral.getRewardWay().equals(BusinessConstant.REFERRAL_AWARD_WAY_FFTC)){
                //进入质检待审核
                business.setBusinessStatus(BusinessConstant.BUS_STATUS_WAIT_FOLLOW);//质检待审核设置待跟进
                business.setBusinessLocation(BusinessConstant.BUS_STORE_REFERRAl);//转介绍库
                business.setBusinessOperate(CustomerRecordConstant.BUS_1009);//当前操作为质检待审核
                businessReferral.setReferralAuditStatus(0);
                //business.setBusinessOrganizationId();
                String content = "新增转介绍商机，进入质检待审核";
                saveBusinessRecord(business, CustomerRecordConstant.BUS_1009, content, user.getId(), null, business.getFollowerId(), null, business.getFollowerOrganizationId(), "", business.getFollowerName());
            }

        }
        repository.save(business);
        repository.save(businessReferral);
        //写入新增商机的备注日志
//      saveBusinessRecord(business, CustomerRecordConstant.BUS_OPERATE_REFERRAL, "新增了转介绍商机", user.getId(), null, business.getFollowerId());
        //对选中的产品做处理
        String productIds = reqParam.get("productIdsTemp") == null ? "" : reqParam.get("productIdsTemp").toString();
        if (StringUtils.isNotBlank(productIds)) {
            String[] idArr = productIds.split(",");
            Map newInfo = new HashMap();
            newInfo.put("businessId", businessId);
            for (String s : idArr) {
                newInfo.put("productId", s);
                businessDao.addBusinessProductByMap(newInfo);
            }
        }
        return businessId;
    }


    /**
     * 新增商机。资源端、商务个人、广泛资源转化、白名单、新媒体接口都使用该方法新增商机
     *
     * @param reqParam 页面参数
     * @param business 页面传入的商机信息
     * @param user     当前操作用户
     * @param addType  新增类型
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Long addSwNewBusiness(Map reqParam, Business business, BusinessReferral businessReferral, User user, String addType) {
        if (null == business) {
            throw new BizException("商机为空，无法操作", 10001);
        }
        if (null == business.getTypeCode()) {
            throw new BizException("商机业态为空，无法操作", 10001);
        }
        if (null == addType) {
            throw new BizException("新增类型为空，无法操作", 10001);
    }
        if (null == user) {
            throw new BizException("新增人为空，无法操作", 10001);
        }
        Long customerId = business.getCustomerId();
        businessReferral.setId(business.getId());
        business.setIsReferral(1);
        String customerPhone = business.getCustomerPhone();
        User receiveUser  = userService.getUserById(businessReferral.getReceiveUserId());
        businessReferral.setReceiveUserName(receiveUser.getName()+receiveUser.getLoginName());//接收人
        businessReferral.setReferralUserName(user.getName()+user.getLoginName());//转介绍人
        Customer customer = null;

        String opportunitytypeCode = BusinessConstant.BUS_OPP_1;
        String busOperate = CustomerRecordConstant.BUS_OPERATE_REFERRAL;
        Map cus = new HashMap();
        DecimalFormat df   = new DecimalFormat("######0.00");
        businessReferral.setRewardWay(reqParam.get("rewardWay").toString());
        BigDecimal point = new BigDecimal(100);
        BigDecimal performanceProportion = new BigDecimal(reqParam.get("performanceProportion")+"").divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);//计算掉库率
        BigDecimal tcProportion = new BigDecimal(reqParam.get("tcProportion")+"").divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);//计算掉库率
//        businessReferral.setPerformanceProportion(performanceProportion);
//        businessReferral.setTcProportion(tcProportion);

        business.setBusinessOperate(busOperate);//当前操作
        //当前跟进人
        business.setFollowerName(receiveUser.getName() + receiveUser.getLoginName());
        business.setFollowerId(receiveUser.getId());
        business.setFollowerOrganizationId(receiveUser.getOrgId());
        business.setIsImportant(1);//默认1次


        //资源端是否立即分配
        String allot = reqParam.get("allot") == null ? "" : reqParam.get("allot").toString();
        if ("1".equals(allot) && !BusinessConstant.BUS_ADD_TYPE_CODE_5.equals(addType)) {
//            //判断是否分配原商务
//            String toLastUser = reqParam.get("toLastUser") == null ? "" : reqParam.get("toLastUser").toString();
//            if (!"1".equals(toLastUser)) {//分配给原商务的传值不为1
//                receiver = null;
//            } else {//分配给原商务，需要判断商务是否可接单
//                //判断商务是否可接单
//                isUserCanReceiveBusiness(receiver);
//            }
            allotBusiness(business, null, user, customer.getLevel(),2);
        }
        //计算预计掉库时间
        businessService.setBusinessWillDropDate(business);
        businessReferral.setReferralType(reqParam.get("referralType")+"");
        business.setDescription(HtmlUtils.htmlEscape(business.getDescription()));
        repository.save(business);
        repository.save(businessReferral);
        //写入新增商机的备注日志
        //saveBusinessRecord(business, busOperate, "新增了转介绍商机", user.getId(), null, business.getFollowerId());
        //对选中的产品做处理
        String productIds = reqParam.get("productIdsTemp") == null ? "" : reqParam.get("productIdsTemp").toString();
        if (StringUtils.isNotBlank(productIds)) {
            String[] idArr = productIds.split(",");
            Map newInfo = new HashMap();
            newInfo.put("businessId", business.getId());
            for (String s : idArr) {
                newInfo.put("productId", s);
                businessDao.addBusinessProductByMap(newInfo);
            }
        }
        //TODO to xuzhe 抛出商机已添加消息，如果影响到启动，请注释掉该行
//        MessageManager.getMessageManager().publishEvent(PublishMessageExchangeNames.BUSINESS_ADDED, business);
        return business.getId();
    }

    /**
     * 商机强制掉库
     *
     * @param lastBusiness 掉库商机
     * @param user         操作人
     * @param dropType     掉库类型，成单掉库或退单掉库
     */
    private void dropBusiness(Business lastBusiness, User user, String dropType) {
        lastBusiness.setBusinessLocation(BusinessConstant.BUS_STORE_DEPARTMENT);
        lastBusiness.setBusinessOperate(dropType);
        lastBusiness.setIsVip(0);
        lastBusiness.setIsImportant(0);
        lastBusiness.setLastFollowRecordTime(new Date());
        lastBusiness.setLastFollowRecordContent("客户被开发，商机强制掉库");
        lastBusiness.setLastFollowRecordUser(user.getName() + user.getLoginName());
        lastBusiness.setUpdaterUser(user);
        lastBusiness.setLoseDeptTime(new Date());
        repository.saveOrUpdate(lastBusiness);
        saveBusinessRecord(lastBusiness, dropType, "客户被开发，商机强制掉库", user.getId(), lastBusiness.getFollowerId(), null, lastBusiness.getFollowerOrganizationId(), null, lastBusiness.getFollowerName(), "");
        User msgUser = repository.get(User.class, lastBusiness.getFollowerId());
//        messageService.sendMessage(msgUser, user, "你的客户【" + lastBusiness.getCustomerName() + "/" + lastBusiness.getCustomerNo() + "】已经被【" + user.getName() + "】新建了商机，因此客户被强制移交给【" + user.getName() + "】", 2, 1);
        sendBusinessMsg(msgUser, user, "SJ_0003", lastBusiness.getCustomerName(), lastBusiness.getCustomerNo(), user.getName() + user.getLoginName(), user.getName());
    }

    /**
     * 发送商机信息提示
     *
     * @param receiverUser        接收人
     * @param sendUser            发送人
     * @param messageTemplateCode 模版code
     * @param vals                参数
     */
    private void sendBusinessMsg(User receiverUser, User sendUser, String messageTemplateCode, String... vals) {
        BizExceptionUtil.isException(null == vals, "短信参数不能为空");
        messageService.sendMessageReady(receiverUser, sendUser, vals, messageTemplateCode);
    }


    /**
     * 保存一般的商机备注信息，即当商机跟进人或状态没有变动时调用该方法
     *
     * @param business      商机信息
     * @param recordType    备注类型
     * @param content       备注内容
     * @param operateUserId 操作人
     * @param oldFollowerId 商机原跟进人
     * @param newFollowerId 商机新跟进人
     */
    @Transactional(propagation = Propagation.REQUIRED)
    private void saveBusinessRecord(Business business, String recordType, String content, Long operateUserId, Long oldFollowerId, Long newFollowerId) {
        saveBusinessRecord(business, recordType, content, operateUserId, oldFollowerId, newFollowerId, null, null, "", "");
    }

    /**
     * 保存有附件的备注调用该方法
     *
     * @param business         商机信息
     * @param recordType       操作类型
     * @param content          备注内容
     * @param operateUserId    操作人id
     * @param oldFollowerId    原商机跟进人id
     * @param newFollowerId    新商机跟进人id
     * @param oldFollowerOrgId 原商机跟进人部门id
     * @param newFollowerOrgId 新商机跟进人部门id
     * @param oldFollowerName  原商机跟进人名字
     * @param newFollowerName  新商机跟进人名字
     * @param fileId           附件id
     */
    @Transactional(propagation = Propagation.REQUIRED)
    private void saveBusinessFileRecord(Business business, String recordType, String content, Long operateUserId, Long oldFollowerId, Long newFollowerId, Long oldFollowerOrgId, Long newFollowerOrgId, String oldFollowerName, String newFollowerName, String fileId) {
        Map recordMap = new HashMap();
        recordMap.put("tableName", Business.TABLE_NAME);
        recordMap.put("tableId", business.getId());
        recordMap.put("cusId", business.getCustomerId());
        recordMap.put("recordType", recordType);
        recordMap.put("content", content);
        recordMap.put("fromUserId", oldFollowerId);//旧跟进人
        recordMap.put("toUserId", newFollowerId);//新的跟进人
        recordMap.put("ext1", business.getBusinessStage());//商机所在库
        recordMap.put("ext2", business.getBusinessLocation());//商机当前阶段
        recordMap.put("ext4", business.getBusinessStatus());//商机当前状态
        recordMap.put("ext3", business.getNo());//商机编号
        recordMap.put("ext5", fileId);//附件id
        recordMap.put("fromUserOrgId", oldFollowerOrgId);//出库人部门id
        recordMap.put("toUserOrgId", newFollowerOrgId);//入库人部门id
        JSONObject json = new JSONObject();
        json.put("count",business.getIsImportant()+""); //当前分配次数
        if (StringUtils.isNotBlank(oldFollowerName) || StringUtils.isNotBlank(newFollowerName)) {
            if (StringUtils.isNotBlank(oldFollowerName)) {
                json.put("outUser", oldFollowerName);
            }
            if (StringUtils.isNotBlank(newFollowerName)) {
                json.put("inUser", newFollowerName);
                json.put("inUserOrg", TranslateMapUtil.translateOrgName(business.getFollowerOrganizationId()));
                json.put("inUserbzName", TranslateMapUtil.translateOrgName(business.getBusinessOrganizationId()));
            }
        }
        recordMap.put("altJson", JsonUtil.obj2Json(json));
        recordMap.put("operateUser", operateUserId);
        customerRecordService.saveCustomerRecord(recordMap);
    }

    /**
     * 保存有出入库操作的备注/有商机跟进人变动的应该掉这个方法
     *
     * @param business         商机信息
     * @param recordType       操作类型
     * @param content          备注内容
     * @param operateUserId    操作人id
     * @param oldFollowerId    原商机跟进人id
     * @param newFollowerId    新商机跟进人id
     * @param oldFollowerOrgId 原商机跟进人部门id
     * @param newFollowerOrgId 新商机跟进人部门id
     * @param oldFollowerName  原商机跟进人名字
     * @param newFollowerName  新商机跟进人名字
     */
    private void saveBusinessRecord(Business business, String recordType, String content, Long operateUserId, Long oldFollowerId, Long newFollowerId, Long oldFollowerOrgId, Long newFollowerOrgId, String oldFollowerName, String newFollowerName) {
        saveBusinessFileRecord(business, recordType, content, operateUserId, oldFollowerId, newFollowerId, oldFollowerOrgId, newFollowerOrgId, oldFollowerName, newFollowerName, "");
    }


    /**
     * 商机自动分配，并写入分配日志，发送提醒短信给商务
     *
     * @param business      被分配的商机
     * @param receiver      商机接收人
     * @param allotUser     分配人，即当前操作人
     * @param customerLevel 客户等级，自动分配时需要传入
     * @param allotType     1人工，2自动
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void allotBusiness(Business business, User receiver, User allotUser, String customerLevel,int allotType) {
        if (null == receiver) {//接收人为空，则调用自动分配的接口
            if (null == business.getBusinessOrganizationId()) {
                throw new BizException("商机未选择受理事业部，无法分配", 10001);
            }
            JSONObject map = new JSONObject();
            map.put("opportunityId", business.getId());
            customerLevel = StringUtils.isBlank(customerLevel) ? "0" : customerLevel.trim();
            customerLevel = customerLevel.replace("CUS_KHZZ_STAR_", "");//等级的格式应该为CUS_KHZZ_STAR_3.5
            BigDecimal lev = new BigDecimal(0);//默认都是0星资源
            try {
                lev = new BigDecimal(customerLevel);
            } catch (Exception e) {
            }
            map.put("customerLevel", lev.setScale(1, BigDecimal.ROUND_DOWN).doubleValue());
            map.put("businessUnitId", business.getBusinessOrganizationId());
            JSONObject addtionInfo = new JSONObject();
            addtionInfo.put("allotUserId", allotUser.getId());
            map.put("addtionInfo", addtionInfo);
            try {
                String rest = HttpRequest.httpPostWithJSON(ConfigLoader.getConfigLoader().getVaule("autodispatchurl").trim(), map);
                Map result = JsonUtil.json2Obj(rest, Map.class);
                if (!result.get("code").toString().equals("0")) {//返回结果不为0则分配失败
                    throw new BizException("自动分配失败，请稍后再试!", 10001);
                }
            } catch (Exception e) {
                throw new BizException("自动分配请求失败，请提醒管理员检查分配服务!", 10001);
            }
            business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_AUTO_ALLOT);//将当前操作改为进入分配队列
            business.setUpdaterUser(allotUser);//将分配人写入update数据中，用于在界面展示
            return;
        }
        if (!business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_NEW)) {
            throw new BizException("商机已完成分配，不能再次分配!", 10001);
        }
        business.setFirstDistributionTime(new Date());
        business.setFirstFollowerId(receiver.getId());//第一次接收人
        business.setFirstFollowerOrganizationId(receiver.getOrgId());//第一次接收人部门id
        business.setDistributionTime(new Date());//本次分配时间
        business.setFollowerName(receiver.getName() + receiver.getLoginName());
        business.setFollowerId(business.getFirstFollowerId());
        business.setFollowerOrganizationId(receiver.getOrgId());
        business.setBusinessStatus(BusinessConstant.BUS_STATUS_WAIT_FOLLOW);//待跟进
        business.setBusinessLocation(BusinessConstant.BUS_STORE_EMP);//个人库
        business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_ALLOT);//当前操作为分配
        business.setSingleUserId(allotUser.getId());
        business.setWayCode(BusinessConstant.BUS_WAY_CODE_1);//分配

        String content = (allotType == 2 ? "自动":"人工")+"分配商机";
        //将分配操作写在最后一次备注上
        business.setLastFollowRecordContent(content);
        business.setLastFollowRecordTime(new Date());
        business.setLastFollowRecordUser(allotUser.getName() + allotUser.getLoginName());
        //写上新增备注，发送短信通知
        saveBusinessRecord(business, CustomerRecordConstant.BUS_OPERATE_ALLOT, content, allotUser.getId(), null, business.getFollowerId(), null, business.getFollowerOrganizationId(), "", business.getFollowerName());
//        messageService.sendMessage(receiver, allotUser, "您的商机【" + business.getNo() + "】在【" + DateUtil.dateToString(business.getDistributionTime()) + "】分配给你，请你尽快跟进", 3, 2);
        sendBusinessMsg(receiver, allotUser, "SJ_0001", receiver.getName(), business.getNo(), DateUtil.dateToString(business.getDistributionTime()));


    }


    /**
     * 转介绍商机自动分配，并写入分配日志，发送提醒短信给商务
     *
     * @param business      被分配的商机
     * @param receiver      商机接收人
     * @param allotUser     分配人，即当前操作人
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void allotReferralBusiness(Business business, User receiver, User allotUser,User referralUser,String flag) {
       // business.setFirstDistributionTime(new Date());
        business.setFirstFollowerId(receiver.getId());//第一次接收人
        business.setFirstFollowerOrganizationId(receiver.getOrgId());//第一次接收人部门id
        business.setDistributionTime(new Date());//本次分配时间
        business.setFollowerName(receiver.getName() + receiver.getLoginName());
        business.setFollowerId(business.getFirstFollowerId());
        business.setFollowerOrganizationId(receiver.getOrgId());
        business.setBusinessStatus(BusinessConstant.BUS_STATUS_WAIT_FOLLOW);//待跟进
        business.setBusinessLocation(BusinessConstant.BUS_STORE_EMP);//个人库

        business.setSingleUserId(allotUser.getId());
        business.setWayCode(BusinessConstant.BUS_WAY_CODE_4);//转介绍

        String content = "";
        String record = "";
        if(("1").equals(flag)){
            content = "新增并分配转介绍商机";
            record = CustomerRecordConstant.BUS_OPERATE_REFERRAL;
            business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_REFERRAL);//当前操作为转介绍

        }else if("2".equals(flag)){
            if(null != receiver.getDisableCutoffTime() && receiver.getDisableCutoffTime().getTime()>new Date().getTime()){
                throw new BizException("商务在"+DateUtil.dateToString(receiver.getDisableCutoffTime(),"yyyy-MM-dd HH:mm:ss")+"之前处于被禁用状态，无法接收资源", 10001);
            }
            business.setUpdaterUser(allotUser);
            content = "质检审核通过并分配转介绍商机";
            record = CustomerRecordConstant.BUS_IN_1009;
            business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_REFERRAL);//当前操作为转介绍
        }
        //将分配操作写在最后一次备注上
        business.setLastFollowRecordContent(content);
        business.setLastFollowRecordTime(new Date());
        business.setLastFollowRecordUser(allotUser.getName() + allotUser.getLoginName());
        //写上新增备注，发送短信通知
        saveBusinessRecord(business, record, content, allotUser.getId(), null, business.getFollowerId(), null, business.getFollowerOrganizationId(), "", business.getFollowerName());
//        messageService.sendMessage(receiver, allotUser, "您的商机【" + business.getNo() + "】在【" + DateUtil.dateToString(business.getDistributionTime()) + "】分配给你，请你尽快跟进", 3, 2);
//        messageService.sendMessage(receiver, allotUser, "商机" + business.getNo() + "是转介绍商机，在" + DateUtil.dateToString(business.getDistributionTime()) + "分配给您，请尽快跟进。成单后请自觉划分利润业绩，谢谢。", 1);
        //接收人
        sendBusinessMsg(receiver, allotUser, "SJ_ZJS_0003", business.getNo(), DateUtil.dateToString(business.getDistributionTime()));
     //转介绍人
        sendBusinessMsg(referralUser, allotUser, "SJ_ZJS_0001",business.getNo(), receiver.getName() + receiver.getLoginName());

    }
        

    /**
     * 判断商务是否可以接单，若不能接单抛出未接单原因的异常
     *
     * @param ruser 接单用户
     */
    private void isUserCanReceiveBusiness(User ruser, User ouser) {
        if (null == ruser) {
            throw new BizException("商务不存在，不能分配商机", 10001);
        }
        if (ruser.getLocked() != 0) {//0、正常；1、锁定；2、离职；默认：0、正常
            String msg = "商务状态异常，不能分配商机";
            if (ruser.getLocked() == 1) {
                msg = "商务被锁定，不能分配商机";
            } else if (ruser.getLocked() == 2) {
                msg = "商务已经离职，不能分配商机";
            }
            throw new BizException(msg, 10001);
        }
        //todo 暂时注释掉
//        String onlineStateCodes = ConfigLoader.getConfigLoader().getVaule("onlineUserCodes").trim();
//        List<String> onlineStateCodeArray = Arrays.asList(onlineStateCodes.split(";"));
//        if (StringUtils.isBlank(ruser.getStateType()) || !onlineStateCodeArray.contains(ruser.getStateType())) {
//            throw new BizException("商务当前不在线，不能分配商机", 10001);
//        }
        //判断是否设置接单规则
        UserSetting us = repository.get(UserSetting.class, ruser.getId());
        if (null == us || null == us.getMonthNum()) {
            throw new BizException("商务未设置接单规则，无法接单", 10001);
        }
        // 判断今日是否可以接单
        if (null == us.getIsReceive() || us.getIsReceive() != 1) {
            // 获取不可以接单的原因
            String reson = "商务已关闭接单，无法接单";
            if (null != us.getIsForce() && 0 != us.getIsForce()) {//强制不接单不为空
                reson = us.getIsForce() == 1 ? "商务昨日值班，今日不再分资源。" : "商务昨日掉库率达到上限，今日不能接收资源";
            }
            throw new BizException(reson, 10001);
        }

        //redis判断商务5分钟内是否有操作，没有的话代表不在线
        //获取用户最后一次操作时间戳
        Long timestemp = CacheManager.getOperator().get(Constants.USER_SESSION_LAST_OPT_PREFIX + ruser.getId(), Long.class);
        timestemp = null == timestemp ? 0L : timestemp;
        try {
            TreeBook tb = treeBookService.queryTreeBookByCode("LXFZS");
            //获取最大间隔时间
            Long maxIdle = (null == tb || tb.getStatus() != 1 || StringUtils.isBlank(tb.getExt1())) ? 99999L : Long.valueOf(tb.getExt1());
            maxIdle = 1000 * 60 * maxIdle;
            //如果超过了最大间隔
            if (System.currentTimeMillis() - timestemp > maxIdle) {
                throw new BizException("商务当前已掉线，不能分配商机", 10001);
            }
        } catch (Exception e) {
            logger.error("判断商务是否在线出现异常：" + e.getMessage());
        }


        //判断月接单量
//        List<Map> counts = businessAllotCountService.searchUserAllotRecord(ruser.getId(), DateUtil.dateToString(new Date(), "yyyyMM"));
//        if (null != counts && !counts.isEmpty()) {
//            Integer all = 0;
//            for (Map count : counts) {
//                all += Integer.valueOf(count.get("allotnumber").toString());
//            }
//            if (all >= us.getMonthNum()) {
//                throw new BizException("商务月接单量已满，无法接单", 10001);
//            }
//        }

    }
     

    /**
     * 退回商机
     *
     * @param businessId     商机id集合
     * @param currentLoginUser 操作人
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void referralBusiness(String businessId,User currentLoginUser) {
        if (StringUtils.isBlank(businessId)) {
            throw new BizException("没找到商机", 10001);
        }
        Business business = getBusinessById(Long.valueOf(businessId));
        BusinessReferral businessReferral = businessReferralService.getBusinessReferralById(Long.valueOf(businessId));
        if (business.getFollowerId().longValue() != currentLoginUser.getId()) {
            throw new BizException("你不是商机【" + business.getNo() + "】的跟进人，不能进行退回", 10001);
        }
        if (!BusinessConstant.BUS_STATUS_WAIT_FOLLOW.equals(business.getBusinessStatus())) {
            throw new BizException("只有待跟进的商机才能退回", 10001);
        }
        //       sendBusinessMsg(repository.get(User.class, Long.valueOf(map.get("userid").toString())), currentLoginUser, "SJ_0013", currentLoginUser.getName(), business.getNo());
        businessReferral.setReturnNum(NumberUtils.toInt(businessReferral.getReturnNum()+"")+1);
        businessReferral.setReturnTime(new Date());
        businessReferral.setCurrentReturnUserId(currentLoginUser.getId());
        businessReferral.setCurrentReturnOrgId(currentLoginUser.getOrgId());
        businessReferral.setCurrentReturnUserName(currentLoginUser.getName()+currentLoginUser.getLoginName());
        business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_REFERRAL_RETURN);//
        business.setIsReturn(CustomerRecordConstant.BUS_OPERATE_REFERRAL_RETURN);//退回
        business.setUpdaterUser(currentLoginUser);
        business.setLastFollowRecordTime(new Date());
        business.setBusinessLocation(BusinessConstant.BUS_STORE_REFERRAl);
        business.setLastFollowRecordUser(currentLoginUser.getName() + currentLoginUser.getLoginName());
        saveBusinessRecord(business, CustomerRecordConstant.BUS_OPERATE_REFERRAL_RETURN,  "退回了转介绍商机", currentLoginUser.getId(), business.getFollowerId(), null, business.getFollowerOrganizationId(), null, business.getFollowerName(), "");
        repository.saveOrUpdate(business);
        repository.saveOrUpdate(businessReferral);
        //转介绍人退回短信
        User referralUser = this.repository.get(User.class,businessReferral.getReferralUserId());

        sendBusinessMsg(referralUser, currentLoginUser, "SJ_ZJS_0002",business.getNo(),currentLoginUser.getLoginName(), DateUtil.dateToString(business.getDistributionTime()));
      //  sendBusinessMsg(receiver, allotUser, "SJ_ZJS_0001", receiver.getName(), business.getNo(), DateUtil.dateToString(business.getDistributionTime()));

    }


    /**
     * 发放红包
     * @param businessIds     商机id集合
     * @param currentLoginUser 操作人
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void referralRed(String businessIds,User currentLoginUser) {
        String[] ids = businessIds.split(",");
        for(String id: ids) {
            if (StringUtils.isBlank(id)) {
                throw new BizException("没找到商机", 10001);
            }
            BusinessReferral businessReferral = businessReferralService.getBusinessReferralById(Long.valueOf(id));
            if(null!=businessReferral.getIsFa()&&businessReferral.getIsFa()==1){
                throw new BizException("不能再次发放红包", 10001);
            }
            businessReferral.setIsFa(1);
            businessReferral.setFaTime(new Date());
            repository.saveOrUpdate(businessReferral);
        }

    }

    /**
     * 发放提成
     * @param businessIds     商机id集合
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void referralTic(String businessIds,ReferralRecord rr ) {
        String[] ids = businessIds.split(",");
        for(String id: ids) {
            if (StringUtils.isBlank(id)) {
                throw new BizException("没找到核款", 10001);
            }
            ReferralRecord referralRecord = businessReferralService.getReferralRecordById(Long.parseLong(id));;
            if(referralRecord.getStatus()==1){
                throw new BizException("不能再次发放提成", 10001);
            }
            referralRecord.setStatus(1);
            referralRecord.setFaTime(new Date());
            referralRecord.setPracticalMoney(rr.getPracticalMoney());
            repository.saveOrUpdate(referralRecord);
        }

    }


    /**
     * 再次转介绍
     *
     * @param businessIds 商机ID
     * @param content     内容
     */
    public void referralBus(String businessIds, String content,User receiveUser, User user,String type) {
        String[] ids = businessIds.split(",");
        for (String id : ids) {
            Business business = this.repository.get(Business.class, Long.parseLong(id));
            BusinessReferral businessReferral = this.repository.get(BusinessReferral.class, Long.parseLong(id));
            if (null != business) {
                business.setDistributionTime(new Date());//分配时间
                business.setLastFollowRecordContent(content);
                business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_REFERRAL);//转介绍
                business.setBusinessLocation(BusinessConstant.BUS_STORE_EMP);//个人库
                business.setIsReturn(CustomerRecordConstant.BUS_OPERATE_REFERRAL_RECEIVE);
                business.setBusinessStatus(BusinessConstant.BUS_STATUS_WAIT_FOLLOW);//待跟进
                business.setFollowerId(receiveUser.getId());
                business.setFollowerName(receiveUser.getName()+receiveUser.getLoginName());
                business.setFollowerOrganizationId(receiveUser.getOrgId());
                business.setLastFollowRecordTime(new Date());
                business.setLastFollowRecordUser(user.getName() + user.getLoginName());
                business.setLastFollowRecordContent(content);
                business.setIsReferral(1);
                if(null!=type&&type.equals("1")){
                    business.setIsImportant(business.getIsImportant()+1);//加分配次数
                }else{
                    business.setIsImportant(business.getIsImportant());
                }
                //查询退回过该条数据的商务
                Map<String,Object> map = new HashMap();
                map.put("businessIds",business.getId());
                map.put("recordType","'"+CustomerRecordConstant.BUS_OPERATE_REFERRAL_RETURN+"'");
                List<Map> reMap = businessDao.listBusinessRecordByMap(map);//查询所有被退回该条商机的商务
                for(Map strmap:reMap){
                    if(receiveUser.getId().equals(strmap.get("fromuserid")) ){
                        throw new BizException("不能再次转介绍给该商务", 10001);
                    }
                }
                if(null != receiveUser.getDisableCutoffTime() && receiveUser.getDisableCutoffTime().getTime()>new Date().getTime()){
                    throw new BizException("商务在"+DateUtil.dateToString(receiveUser.getDisableCutoffTime(),"yyyy-MM-dd HH:mm:ss")+"之前处于被禁用状态，无法接收资源", 10001);

                }
//                if(businessReferral.getCurrentReturnUserId().equals(receiveUser.getId()) ){
//                    throw new BizException("不能再次转介绍给该商务", 10001);
//                }
                businessDao.updateByHiber(business);
                businessReferral.setReceiveOrgId(receiveUser.getOrgId());
                businessReferral.setReceiveUserId(receiveUser.getId());
                businessReferral.setReceiveUserName(receiveUser.getName()+receiveUser.getLoginName());
                businessReferral.setIsReceive(1);
                this.repository.saveOrUpdate(businessReferral);
                saveBusinessRecord(business, CustomerRecordConstant.BUS_OPERATE_REFERRAL, content,user.getId(), businessReferral.getCurrentReturnUserId(), receiveUser.getId(), businessReferral.getCurrentReturnOrgId(), receiveUser.getOrgId(), businessReferral.getCurrentReturnUserName(),receiveUser.getName()+""+receiveUser.getLoginName());

            // messageService.sendMessage(receiver, allotUser, "您的商机【" + business.getNo() + "】在【" + DateUtil.dateToString(business.getDistributionTime()) + "】分配给你，请你尽快跟进", 3, 2);
                User referralUser = this.repository.get(User.class,businessReferral.getReferralUserId());
            //    messageService.sendMessage(receiveUser, user, "商机" + business.getNo() + "是转介绍商机，在" + DateUtil.dateToString(business.getDistributionTime()) + "分配给您，请尽快跟进。成单后请自觉划分利润业绩，谢谢。", 1);
                //接收人
                sendBusinessMsg(receiveUser, user, "SJ_ZJS_0003",business.getNo(), DateUtil.dateToString(business.getDistributionTime()));
                //转介绍人
                sendBusinessMsg(referralUser, receiveUser, "SJ_ZJS_0001",business.getNo(), receiveUser.getName()+receiveUser.getLoginName());
                
                // 给电销分配人员推送消息
        		if (business.getDxAllotUserId() != null) {
        			String[] msgs = { business.getNo(), receiveUser.getName(), receiveUser.getLoginName() };
        			messageService.sendMessageReady(userService.getUserById(business.getDxAllotUserId()), receiveUser, msgs, "SJ_ZJS_JD");
        		}
            } else {
                throw new BizException("当前商机不存在", 10001);

            }
        }

    }


    /**
     * 修改转介绍人
     *
     * @param businessId 商机ID
     * @param content     内容
     */
    public void referralUpdate(String businessId, String content,String referralType,User referralUser,User loginuser) {
        Business business = this.repository.get(Business.class, Long.parseLong(businessId));
        if(business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_ORDER_SUCCESSED)){
            throw new BizException("已成单商机不能修改转介绍人", 10001);
        }
            BusinessReferral businessReferral = this.repository.get(BusinessReferral.class, Long.parseLong(businessId));
                businessReferral.setReferralOrgId(referralUser.getOrgId());
                businessReferral.setReferralUserId(referralUser.getId());
                businessReferral.setUpdaterUser(loginuser);
                businessReferral.setReferralType(referralType);
                businessReferral.setReferralUserName(referralUser.getName()+referralUser.getLoginName());
        Long orgId = organizationService.getOrganizationDepartmentId(referralUser.getOrgId());
        businessReferral.setReferralOrganizationId(orgId);
        if(!TranslateMapUtil.translateOrgName(orgId).equals("null")&&TranslateMapUtil.translateOrgName(orgId).length()>0) {
            businessReferral.setReferralOrganizationName(TranslateMapUtil.translateOrgName(orgId));
        }
                this.repository.saveOrUpdate(businessReferral);
        saveBusinessRecord(business, CustomerRecordConstant.BUS_OPERATE_EDIT,"修改了转介绍人",loginuser.getId(),null,null);


    }

    public void auditQaBusiness(String id,String status,User user){
        Business business = this.repository.get(Business.class, Long.parseLong(id));
        BusinessReferral businessReferral  = this.repository.get(BusinessReferral.class,Long.parseLong(id));
        if (null != business && null != businessReferral) {
            if(StringUtils.isNotBlank(status)) {
                businessReferral.setReferralAuditStatus(Integer.parseInt(status));
                businessReferral.setAuditUserId(user.getId());
                if (Integer.parseInt(status) == 1){
                    //审核通过
                    User referralUser = userService.getUserById(businessReferral.getReferralUserId());//转介绍人
                    User receiveUser = userService.getUserById(businessReferral.getReceiveUserId());//接收人
                    business.setIsReturn(CustomerRecordConstant.BUS_OPERATE_REFERRAL_RECEIVE);//接收
                    allotReferralBusiness(business, receiveUser, user, referralUser,"2");
                    //计算预计掉库时间
                    businessService.setBusinessWillDropDate(business);
                }else if(Integer.parseInt(status) == 2){
                    //删除
                    business.setBusinessStatus(BusinessConstant.BUS_STATUS_DEPT_SING);//部门待抢单
                    business.setBusinessLocation(BusinessConstant.BUS_STORE_DEPARTMENT);//事业部库
                    business.setBusinessOperate(CustomerRecordConstant.BUS_OUT_1009);//质检删除掉库


                    business.setIsVip(0);
                    business.setIsImportant(0);
                    business.setLastFollowRecordTime(new Date());
                    business.setLastFollowRecordContent("质检审核删除商机，商机强制掉库");
                    business.setLastFollowRecordUser(user.getName() + user.getLoginName());
                    business.setFollowerId(user.getId());
                    business.setFollowerName(user.getName() + user.getLoginName());
                    business.setUpdaterUser(user);
                    business.setLoseDeptTime(new Date());
                    repository.saveOrUpdate(business);

                    if(null != businessReferral){
                        businessReferral.setReferralTime(null);
                        repository.saveOrUpdate(businessReferral);
                    }

                    //判断当前商机是不是客户的最近商机，是的话就把客户加入到事业部库里面去
                    Customer customer = customerApiService.getCustomerById(business.getCustomerId());
                    if (null != customer.getLastBusId() && customer.getLastBusId().longValue() == business.getId().longValue()) {
                        //新增事业部客户数据
                        DepartmentCustomer dc = departmentCustomerService.getDepartmentCustomerByCustomerId(business.getCustomerId());
                        if (null == dc) {
                            Map dcMap = new HashMap();
                            dcMap.put("operateUser", user);
                            dcMap.put("businessId", business.getId());
                            dcMap.put("dropUserId", user.getId());
                            dcMap.put("customerId", business.getCustomerId());
                            dcMap.put("organizationId", business.getBusinessOrganizationId());
                            dcMap.put("dropWay", CustomerRecordConstant.BUS_OUT_1009);//质检删除掉库
                            departmentCustomerService.addDepartmentCustomer(dcMap);
                        }
                    }
                    saveBusinessRecord(business, CustomerRecordConstant.BUS_OUT_1009, "质检审核删除商机，商机强制掉库", user.getId(), business.getFollowerId(), null, business.getFollowerOrganizationId(), null, business.getFollowerName(), "");
                }
            }

        }else {
            throw new BizException("当前商机不存在", 10001);

        }

    }

}
